import {useCallback, useRef, useState} from "react";
import {ActionType} from "@ant-design/pro-components";
import {getPrincessList} from "@/services/ant-design-pro/api";
import {message} from "antd";
import {LocalStorageService} from "@/utils";

type dataList = {
  success: boolean,
  total: number,
  data: any[]
}

export const usePrincessList = () => {
  const {isAdmin} = LocalStorageService.getItem("loginInfo")
  // 表格实体的引用
  const actionRef = useRef<ActionType>();
  const [currentItem, setCurrentItem] = useState<API.PrincessListApi>({
    name: "",
    age: 0,
    gender: 1,
    height: 0,
    weight: 0,
    bra: "",
    service_hours: "",
    price: "",
    description: "",
  })
  const [loadingList, setLoadingList] = useState({
    searchLoading: false,
  })
  const [openList, setOpenList] = useState({
    detailOpen: false,
    princessListOpen: false,
  })
  const [activeTabKey, setActiveTabKey] = useState<string>('basic');
  const [ordered, setOrdered] = useState<API.PrincessListApi[]>([])
  const [showOrdered, setShowOrdered] = useState<API.PrincessListApi[]>(ordered)
  const [searchInput, setSearchInput] = useState('')

  const handleFetchListData: ({current, pageSize, ...params}: {
    current: any;
    pageSize: any;
    [p: string]: any
  }) => Promise<any> = useCallback(async ({current, pageSize, ...params}) => {
    const retData: dataList = {
      success: false,
      total: 0,
      data: []
    };
    const customParams = {
      page: current,
      page_size: pageSize,
      name: params['name'] ?? '',
      age: params['age'] ?? '',
      gender: params['gender'] ?? '',
      height: params['height'] ?? '',
      weight: params['weight'] ?? '',
      bra: params['bra'] ?? '',
      price: params['price'] ?? '',
    };

    try {
      const response = await getPrincessList(customParams);

      const data = response.data;
      if (!data) {
        return
      }

      retData.success = true;
      retData.total = data.length;
      retData.data = data ?? [];

    } catch (e) {
      message.error('数据请求异常');
    }
    return retData;
  }, [])

  const handlerOpenDetail = (item: API.PrincessListApi) => {
    setCurrentItem(item)
    setOpenList(prev => ({
      ...prev,
      detailOpen: true,
    }))
  }

  const handlerClose = (type: string) => {
    if (type === 'detail') {
      setOpenList(prev => ({
        ...prev,
        detailOpen: false,
      }))
    }
    if (type === 'list') {
      setOpenList(prev => ({
        ...prev,
        princessListOpen: false,
      }))
    }
  }

  const handlerCardTabChange = (key: string) => setActiveTabKey(key);

  const handlerPlaceAnOrder = (item: API.PrincessListApi) => {
    if (!item) return;
    // 检查是否已存在
    const isNew = ordered.some(existing => existing?.id === item.id);

    if (!isNew) {
      // @ts-ignore
      setOrdered(prev => [...prev, item]);
      setShowOrdered(prev => [...prev, item])
    }
  }

  const handlerShowOrder = () => {
    setOpenList(prev => ({
      ...prev,
      princessListOpen: true,
    }))
  }

  const handlerDelPrincess = (item: API.PrincessListApi) => {
    const newOrder = ordered.filter(order => order?.id !== item?.id)
    setOrdered(newOrder)
    setShowOrdered(newOrder)
    message.open({
      type: 'success',
      content: "删除成功",
    })
    setSearchInput('')
  }

  const handlerSearchInput = (e: any) => setSearchInput(e.target.value)

  const handlerSearchPrincess = () => {
    setLoadingList(prev => ({...prev, loadingList: true}))
    if (searchInput) {
      const newOrder = ordered.filter(order => order.name === searchInput)
      setShowOrdered(newOrder)
      return
    }
    setShowOrdered(ordered)
    setLoadingList(prev => ({...prev, loadingList: false}))
  }

  return {
    actionRef,
    isAdmin,
    currentItem,
    loadingList,
    searchInput,
    openList,
    activeTabKey,
    ordered,
    showOrdered,
    handleFetchListData,
    handlerOpenDetail,
    handlerClose,
    handlerCardTabChange,
    handlerPlaceAnOrder,
    handlerShowOrder,
    handlerDelPrincess,
    handlerSearchInput,
    handlerSearchPrincess,
  }
}
